package com.zxd.interview.eightthread.stop;

/**
 * 停止线程的两种正确方法：
 * 1. 优先选择：传递中断（抛异常）
 * - catch整个run内部的代码，所有的子方法抛出异常即可
 * - 不想或无法传递：恢复中断（子方法内部处理）
 */
public class RunwayStopThreadWithTwiceMethod implements Runnable {


    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RunwayStopThreadWithTwiceMethod());
        thread.start();
        thread.sleep(500);
        // 线程不响应停止
        thread.interrupt();
        thread.sleep(500);
        // 线程不响应停止
        thread.interrupt();
    }

    @Override
    public void run() {
        try {
            throwExceptionMethod1();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        throwExceptionMethod2();
    }

    private void throwExceptionMethod1() throws InterruptedException {
        int num = 0;
        // !Thread.currentThread().isInterrupted() 这一段不是判断的关键
        while ( num <= Integer.MAX_VALUE / 2) {
            if (num % 100 == 0) {
                System.out.println("num =>" + num);
                Thread.sleep(100);
            }
            num++;
        }
        System.out.println("执行完成");
    }

    private void throwExceptionMethod2() {
        int num = 0;
        // 内部捕获异常，必须要添加：!Thread.currentThread().isInterrupted()
        while (!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE / 2) {
            if (num % 100 == 0) {
                System.out.println("num =>" + num);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            num++;
        }
        System.out.println("执行完成");
    }
}


